<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Baijia;
use app\common\library\wxPay;

/**
 * 录播课程
 */
class Course extends Api
{

    protected $noNeedLogin = ['list', 'info', 'buy', 'getTecollect','getCollect'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    // 获取课程列表
    public function list()
    {   
        $data = [];
        $classid = $this->request->request('classid',0);//分类ID
        $page = $this->request->request('page',1);//分页
        //$userid = $this->request->request('userid');//用户ID
        $pageNum  = 6;//每页个数

        $where = array();
        $where['status'] = 1;
        if(!empty($classid)){
            $where['classid'] = $classid;
        }

        $start = ($page-1)*$pageNum;
        //查询总页数
        $count = db('course')->where($where)->order('sort', 'desc')->count();
        $maxpages = ceil($count/$pageNum);
        if($page > $maxpages){
            $this->success('最后一页了',$data);
        }

        $course_list = db('course')->where($where)->order('sort', 'desc')->limit($start,$pageNum)->select();
        if(!empty($course_list)){
            foreach($course_list as $key=>$value){
                $course_list[$key]['classid_title'] =model("\app\admin\model\allclass\Allclass")->get_class_name($value['classid']);//分类
                $course_list[$key]['tags'] = model("\app\admin\model\allclass\Tags")->get_tags($value['tags']);
                $course_list[$key]['cover'] = getImagesUrl($value['cover']);
                $course_list[$key]['price'] = price_format($value['price']);
                
            }
        }

        $data = ['maxpages'=>$maxpages,'course_list'=>$course_list];
        $this->success('查询成功',$data);
    }   

    // 课程详情
    public function info()
    {
        $course_id = $this->request->param('course_id');
        $user_id = $this->request->param('userid');//用户ID
        $info = model("\app\admin\model\course\Course")->where('id',$course_id)->find();
        if(!$info){
            $this->error('课程不存在');
        }

        if(empty($user_id)){
            $this->error('用户未登录');
        }

        /*课程讲授教师*/
        $info['classid_title'] =model("\app\admin\model\allclass\Allclass")->get_class_name($info['classid']);//分类
        $info['teacher_info'] = $this->getTeacherInfo($info['teacher_id']);
        $info['price'] = price_format($info['price']);//格式化价格
        $info['cover'] = getImagesUrl($info['cover']);

        /*查询课程章节*/
        $chapters = model("\app\admin\model\course\Chapter")->where([
            'course_id' => $course_id,
            'status' => 1,
        ])->order('is_free','DESC')->select();

        $info['chapters'] = $chapters;

        /*查询课程评价*/
        $c_count = db('course_comment')->where("course_id",$course_id)->count('id');
        $info['c_count'] = $c_count;//评价条数
        
        if(!empty($c_count)){
            $avg_star = db('course_comment')->where("course_id",$course_id)->avg('star');
        }else{
            $avg_star = 0;
        }

        $info['avg_star'] = $avg_star;//平均评价值

        //查询课程销量
        $info['sales'] = 0;
        //判断课程是否被收藏
        $info['is_collect'] = $this->getTecollect($user_id,$course_id);//0没收藏 1收藏过

        $this->success('查询成功',$info);
    }

    /**
     * 收藏或取消收藏
     */
    public function getCollect(){

        $course_id = $this->request->request('course_id');//课程ID
        $userid = $this->request->request('userid');//用户ID

        //是否收藏
        $collect = db('course_collect')->where('user_id', $userid)->where('course_id', $course_id)->count();
        if($collect > 0){
            //取消收藏
            db('course_collect')->where('user_id', $userid)->where('course_id', $course_id)->delete();
            $msg = "取消成功";
        }else{
            //添加收藏
            $data = ['user_id' => $userid, 'course_id' => $course_id, 'createtime' => time()];
            db('course_collect')->insert($data);
            $msg = "收藏成功";
        }

        $this->success($msg,$collect);

    }

    /**
     * 判断是否被收藏
     */

    public function getTecollect($userid = "", $course_id = 0){
        
        $is_collect = 0;//收藏

        if(empty($userid) || empty($course_id)){
            return $is_collect;
        }

        //收藏
        $collect = db('course_collect')->where('user_id', $userid)->where('course_id', $course_id)->count();
        if($collect > 0){
            $is_collect = 1;
        }
        
        return $is_collect;
    }


    /**
     * 购买
     */
    public function buy(){
        
        $course_id = $this->request->param('course_id');//课程ID
        $coupon_id = $this->request->param('coupon_id',0);//优惠券ID
        $user_id = $this->request->param('user_id');//用户ID
        $order_amount = $this->request->param('order_amount');//订单金额
        //$real_amount = $this->request->param('real_amount');//实付金额
        $openid = $this->request->param('openid');//openid

        $uid = $this->auth->id;
        if($user_id != $uid){
           // $this->error('用户信息错误');
        }

        $info = model("\app\admin\model\course\Course")->where('id',$course_id)->find();
        if(!$info){
            $this->error('课程不存在');
        }

        //验证优惠券是否有效
        $coupon_money = 0;//优惠金额
        if(!empty($coupon_id)){
            $coupon_money =  $this->getVerifyCoupon($coupon_id,$user_id);
        }

        //计算实付金额
        $real_amount = $order_amount-$coupon_money;
        if($real_amount < 0){
            $real_amount = 0;//优惠抵扣全部
            $coupon_money = $order_amount;//重置优惠金额为订单金额
        }else{
            //格式化价格
            $real_amount = number_format($real_amount, 2, '.', '');
        }

        //查询是否购买过或者存在未支付订单
        $order_info = model("\app\admin\model\order\CourseOrder")->get_course_order_info($course_id,$user_id);

        if(!empty($order_info['id'])){

            if($order_info['pay_status'] == 1){
                //支付完成
                $msg = "您已购买过此课程，请前往个人中心-》我的课程 进行学习";
                $this->success($msg);

            }else{

                //直接购买成功
                if($real_amount == 0){

                    $p_order_amount = [];
                    $p_order_amount['order_amount'] = $order_amount;//订单金额
                    $p_order_amount['real_amount'] = $real_amount;//实付金额
                    $p_order_amount['discount_amount'] = $coupon_money;//优惠金额
                    $p_order_amount['coupon_id'] = $coupon_id;//优惠券ID

                    $p_order_amount['pay_status'] = 1;//支付状态已完成
                    $p_order_amount['expirytime'] = time();//过期时间
                    $p_order_amount['updatetime'] = time();//修改时间
                    
                    //修改订单信息
                    $upd = db('course_order')->where('id', $order_info['id'])->update($p_order_amount);
                    if($upd){
                        //用户开课
                        $this->addStuCourse($course_id, $user_id, $order_info['id']);
                        //更新优惠券状态
                        if(!empty($coupon_id)){
                           $this->updatecoupon($coupon_id,$order_info['id']); 
                        }
                        $msg = "购买成功，请前往个人中心-》我的课程 进行学习";
                        $this->success($msg);
                    }

                }else{

                    //重新开启订单 有效期重置24小时
                    $p_order_amount = [];
                    $p_order_amount['order_amount'] = $order_amount;//订单金额
                    $p_order_amount['real_amount'] = $real_amount;//实付金额
                    $p_order_amount['discount_amount'] = $coupon_money;//优惠金额
                    $p_order_amount['coupon_id'] = $coupon_id;//优惠券ID

                    $p_order_amount['pay_status'] = 0;//支付状态已完成
                    //$p_order_amount['createtime'] = time();//创建时间
                    $p_order_amount['expirytime'] = time()+24*60*60;//过期时间延迟24小时
                    $p_order_amount['pay_type'] = "wxpay";
                    $p_order_amount['updatetime'] = time();//修改时间
                    
                    //修改订单信息
                    $upd = db('course_order')->where('id', $order_info['id'])->update($p_order_amount);
                    if($upd){
                       
                        //查询paylog记录
                        $pay_log = db('pay_log')->where('order_sn',$order_info['order_sn'])->find();

                        //更新支付数据
                        $new_pay_log = [];
                        $new_pay_log['money'] = $real_amount;
                        $new_pay_log['updatetime'] = time();//修改时间
                        db('pay_log')->where('id', $pay_log['id'])->update($new_pay_log);

                        //调用支付类 发起支付
                        $total_fee = $real_amount*100;//已分为单位
                        $out_trade_no = "C".date("YmdHis")."-".$pay_log['id'];//订单标号
                        //$openid = "oNjbJ5M-dE3KbVo9mtnSXkmGRvBc";
                        $wxPay = new wxPay();
                        $return = $wxPay->getPay($total_fee,$out_trade_no,'JSAPI',$openid,'课程购买');

                        /*
                        echo "<pre>";
                        print_r($return);
                        die;*/
                        $this->success("创建订单成功",$return);

                    }else{
                        $this->error('订单生成失败');
                    }

                }

            }

        }else{

            //生成订单
            $p_order_amount = [];
            $order_sn = getOrderSn();
            $p_order_amount['order_sn'] = $order_sn;//订单编号
            $p_order_amount['user_id'] = $user_id;//用户ID
            $p_order_amount['order_amount'] = $order_amount;//订单金额
            $p_order_amount['real_amount'] = $real_amount;//实付金额
            $p_order_amount['discount_amount'] = $coupon_money;//优惠金额
            $p_order_amount['coupon_id'] = $coupon_id;//优惠券ID
            $p_order_amount['type'] = "coures";
            $p_order_amount['course_id'] = $course_id;//课程ID
            $p_order_amount['pay_status'] = 0;//支付状态已完成
            $p_order_amount['createtime'] = time();//创建时间
            $p_order_amount['expirytime'] = time()+24*60*60;//过期时间延迟24小时
            $p_order_amount['pay_type'] = "wxpay";
                    
            $order_id = db('course_order')->insertGetId($p_order_amount);
            if($order_id){

                //直接购买成功
                if($real_amount == 0){

                    //修改订单信息
                    db('course_order')->where('id', $order_id)->update(['pay_status' => 1,'updatetime'=>time()]);
                    //用户开课
                    $this->addStuCourse($course_id, $user_id, $order_id);
                    //更新优惠券状态
                    if(!empty($coupon_id)){
                        $this->updatecoupon($coupon_id,$order_info['id']); 
                    }
                    $msg = "购买成功，请前往个人中心-》我的课程 进行学习";
                    $this->success($msg);
                }

                //添加paylog
                $pay_log = [];
                $pay_log['user_id'] = $user_id;
                $pay_log['order_sn'] = $order_sn;
                $pay_log['type'] = "course";
                $pay_log['money'] = $real_amount;
                $pay_log['createtime'] = time();//创建时间

                $log_id = db('pay_log')->insertGetId($pay_log);
                if($log_id){

                    //调用支付类 发起支付
                    $total_fee = $real_amount*100;//已分为单位
                    $out_trade_no = "C".date("YmdHis")."-".$log_id;//订单标号
                    //$openid = "";
                    $wxPay = new wxPay();
                    $return = $wxPay->getPay($total_fee,$out_trade_no,'JSAPI',$openid,'课程购买');
                    /*
                    echo "<pre>";
                    print_r($return);
                    die;*/
                    $this->success("创建订单成功",$return);

                }else{
                    $this->error('订单生成失败');
                }

            }else{
                $this->error('订单生成失败');
            } 
        
        }

    }


    /**
    * 获取教师详情
    */
    public function getTeacherInfo($id = ""){
        
        $ret = [];

        if(empty($id)){
            return $ret;
        }else{

            $teacher_info = db('teacher')->where('id', $id)->find();

            $ret['name'] = $teacher_info['name'];
            $ret['nickname'] = $teacher_info['nickname'];
            //$ret['introduce'] = $teacher_info['introduce'];
            $ret['is_live'] = $teacher_info['is_live'];//是否咨询师 1是 0不是
            $ret['grade'] = $teacher_info['grade'];//等级资质
            $ret['field'] = $teacher_info['field'];

            $ret['class_list'] = model("\app\admin\model\allclass\Allclass")->getClassidInfo($teacher_info['classid']);//分类
            $ret['tags_list'] = model("\app\admin\model\allclass\Tags")->gettagsInfo($teacher_info['tags']);//标签

            if(empty($teacher_info['headimg'])){
                $teacher_info['headimg'] = "/uploads/20210329/0de9220466f6ea2f14dde0989cd9fbb0.png";//默认图片
            }
            $ret['headimg'] = getImagesUrl($teacher_info['headimg']);
        }

        return $ret;
    }

    /**
     * 验证优惠券是否有效
     */
    public function getVerifyCoupon($coupon_id = 0, $user_id = 0){

        $coupon_money = 0;//优惠金额

        if(empty($coupon_id) || empty($user_id)){
            return $coupon_money;
        }

        //查询是否可用优惠券
        $coupon = db('coupon_list')->where('id',$coupon_id)->where('user_id',$user_id)->where('status',0)->find();
        if(!empty($coupon['id'])){
           
            //判断优惠券是否可以使用
            $new_time = time();
            if(($coupon['start_time'] <= $new_time) &&  ($new_time <= $coupon['end_time'])){
                return $coupon['money'];
            }else{
                return $coupon_money;
            }

        }else{
            return $coupon_money;
        }

    }


    /**
     * 更新优惠券状态
     * 
     */
    public function updatecoupon($coupon_id = 0, $order_id = 0){

        if(empty($coupon_id)){
            return false;
        }

        //修改信息
        $ret = db('coupon_list')->where('id', $coupon_id)->update(['type' => 'course','order_id' => $order_id,'use_time' => time(),'status' => 1]);

        if($ret){
            return true;
        }else{
            return false;
        }

    }



    /**
     * 给用户开课
     */
    public function addStuCourse($course_id = 0, $user_id = 0, $course_order_id = 0){

        if(empty($course_id) || empty($user_id) || empty($course_order_id)){
            return false;
        }

        $course = db('course_member')->where('course_id',$course_id)->where('user_id',$user_id)->find();
        if(!empty($course['id'])){
            return true;
        }

        $course_member = [];
        $course_member['course_id'] = $course_id;//课程ID
        $course_member['user_id'] = $user_id;//用户ID
        $course_member['course_order_id'] = $course_order_id;//订单ID
        $course_member['role'] = "student";//角色
        $course_member['createtime'] = time();//创建时间

        db('course_member')->insert($course_member);

        return true;
    }


}
